﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription.OP080;
using CKS.PLC.Core.Cache;
using FreeSql;
using FreeSql.Internal.Model;
using Infrastructure;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP80
{
    /// <summary>
    /// 动作编号 3、4
    /// 钎焊炉结束
    /// </summary>
    public class DB1200_Work0304Action : PLCAction
    {
        
        public DB1200_Work0304Action(DecodeValue _value) : base(_value)
        {
           
        }
        public override void Execute()
        {
            var replayDB = 3010;
            var replayAction = 20;
            var result = Value.Value.ToInt();
            
            var replayPos = Value.GetPosition(replayDB, replayAction, 0);
         
            if (result == 1)
            {
                var model =conn.Select<CksHeatTreatment>().OrderByDescending(a => a.Id).First();
                if(model!=null && model.Status ==1 )
                {
                    model.Status = 10;
                    model.EndTime = DateTime.Now;
                    conn.Update<CksHeatTreatment>().SetSource(model).UpdateColumns(a=>new { a.Status,a.EndTime })
                        .ExecuteAffrows();

                    //更新明细结束时间
                    //保存数据到动态表、
                    var palletizerCells1 = conn.Select<CksShelfPalletizer>().Where(a => a.ShelfId == model.ShelfCode1).ToList();
                    var palletizerCells2 = conn.Select<CksShelfPalletizer>().Where(a => a.ShelfId == model.ShelfCode2).ToList();

                    if (model.Status == 10)
                    {
                        SaveProductInfo(model, palletizerCells1);
                        SaveProductInfo(model, palletizerCells2);
                    }




                }

                EventBus.AddLog("OP90热处理结束请求");
                AckWriteInt16(replayPos, 1);
            }
            else
            {
               
                AckWriteInt16(replayPos, 0);
                logger.LogInformation($"OP90热处理结束-确认信号重置");
            }
        }

        private void SaveProductInfo(CksHeatTreatment main, List<CksShelfPalletizer> palletizerCells)
        {
            foreach (var item in palletizerCells)
            {
                if (!item.CoverCode.IsEmpty())
                {
                    //码不为空存入OP90_Data表
                    var vt = conn.Select<CksVirtualTable>().Where(a => a.TableName == "OP90_Data").First();
                    var columnQuery = conn.Select<CksVirtualColumn>().Where(a => a.TableId == vt.Id).OrderBy(a => a.Sequence);
                    var columns = columnQuery.ToList();
                    var table = ServiceCommon.GetFreesqlTableInfo(vt, columns);

                   var model  = conn.Select<object>().AsType(table.Type)
                        .Where(" BatchNo = @BatchNo AND ShelfCode = @ShelfCode AND CoverCode = @CoverCode "
                        ,new { BatchNo = main.BatchNo, ShelfCode = item.ShelfId, CoverCode = item.CoverCode })
                        .First().Adapt<Dictionary<string,object>>();
                   

                    var dict = new Dictionary<string, object>();
                    dict["EndTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    dict["Id"] = model["Id"];

                    UpdateDynamicTableData(table, dict);

                }
            }
        }


        public object UpdateDynamicTableData(TableInfo fsqlTable, Dictionary<string, object> dict)
        {
            object obj = fsqlTable.CreateInstance(dict);
            conn.Update<object>().AsType(fsqlTable.Type)
                                .SetSource(obj).UpdateColumns(a => dict.Keys.ToArray()).ExecuteAffrows();
            return obj;
        }
    }
}
